package com.nowcoder.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

// 压力测试时注释掉(两个注解)
//@Component
//@Aspect
public class ServiceLogAspect {

    private static Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    /**
     * 连接点:所有的业务组件(方法)
     */
    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointcut() {
    }

    // 参数为连接点
    @After("pointcut()")
    public void after(JoinPoint joinPoint) {
        // 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].
        // 获取用户ip : request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes==null){
            logger.info("触发系统通知调用消费者方法");
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        // localhost : 0:0:0:0:0:0:0:1
        String ip = request.getRemoteHost();
        // 获取当前时间
        String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
        // 获取访问的功能组件
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        logger.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
    }
}
